package vpcserver

import (
	"bytes"
	"encoding/binary"
	"io"
	"math/rand"
	"net"
	"os"
	"time"
)

var longLetters = []byte("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

// receive /* 报文解析 */
func receive(conn net.Conn) (*PayLoad, error) {
	p := &PayLoad{}
	header := make([]byte, 11)
	_, err := io.ReadFull(conn, header)
	if err != nil {
		return p, err
	}
	m := BytesToInt(header[0:4])
	v := header[4:5]
	s := header[5:6]
	c := header[6:7]
	hl := BytesToInt(header[7:11])
	h := make([]byte, hl)
	_, err = io.ReadFull(conn, h)
	if err != nil {
		return p, err
	}
	body := make([]byte, 4)
	_, err = io.ReadFull(conn, body)
	if err != nil {
		return p, err
	}
	bl := BytesToInt(body[0:4])
	b := make([]byte, bl)
	_, err = io.ReadFull(conn, b)
	if err != nil {
		return p, err
	}
	p.magic = m
	p.serializer = s
	p.version = v
	p.command = c
	p.headLen = hl
	p.head = h
	p.bodyLen = bl
	p.body = b
	return p, nil
}

// IntToBytes 整形转换成字节
func IntToBytes(n int) []byte {
	x := int32(n)
	//2147483647
	bytesBuffer := bytes.NewBuffer([]byte{})
	binary.Write(bytesBuffer, binary.BigEndian, x)
	return bytesBuffer.Bytes()
}

// BytesToInt 字节转换成整形
func BytesToInt(b []byte) int {
	bytesBuffer := bytes.NewBuffer(b)
	var x int32
	binary.Read(bytesBuffer, binary.BigEndian, &x)
	return int(x)
}

// RandUp 随机字符串，包含 英文字母和数字附加=_两个符号
func randUp(n int) []byte {
	if n <= 0 {
		return []byte{}
	}
	b := make([]byte, n)
	arc := uint8(0)
	if _, err := rand.Read(b[:]); err != nil {
		return []byte{}
	}
	for i, x := range b {
		arc = x & 61
		b[i] = longLetters[arc]
	}
	return b
}
func TelNetIp(address string) (bool, int64) {
	s := time.Now().UnixMilli()
	conn, err := net.DialTimeout("tcp", address, 15*time.Second)
	e := time.Now().UnixMilli()
	if err != nil {
		return false, 0
	} else {
		if conn != nil {
			_ = conn.Close()
			return true, e - s
		} else {
			return false, 0
		}
	}
}
func GetHostName() string {
	name, err := os.Hostname()
	if err != nil {
		return ""
	}
	return name
}
